// src/api/contract.ts
import http from './http';
import { requestWithRetry } from '@/utils/retry';

// 合同接口定义
export interface Contract {
  id: number;
  contractNumber: string;
  supplierId: number;
  contractName: string;
  contractType: 'purchase' | 'service' | 'other';
  startDate: string;
  endDate: string;
  amount: number;
  status: 'active' | 'expired' | 'terminated';
  attachment: string;
  remark: string;
  createdAt: string;
  updatedAt: string;
  supplier?: {
    id: number;
    name: string;
  };
}

export interface ContractQueryParams {
  supplierId?: number;
  status?: string;
  page: number;
  limit: number;
}

export interface ContractListResponse {
  list: Contract[];
  pagination: {
    page: number;
    limit: number;
    total: number;
  };
}

// 获取合同列表
export const getContracts = async (params: ContractQueryParams) => {
  try {
    // 使用重试机制获取合同列表
    const response: any = await requestWithRetry(
      () => http.get('/procurement/contracts', { params }),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: {
        list: response.data?.list || [],
        pagination: response.data?.pagination || {
          page: 1,
          limit: 20,
          total: 0
        }
      }
    };
  } catch (error: any) {
    return {
      success: false,
      data: {
        list: [],
        pagination: null
      },
      message: error.message || '获取合同列表失败'
    };
  }
};

// 获取合同详情
export const getContractDetail = async (id: number) => {
  try {
    // 使用重试机制获取合同详情
    const response = await requestWithRetry(
      () => http.get(`/procurement/contracts/${id}`),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取合同详情失败'
    };
  }
};

// 创建合同
export const createContract = async (data: Omit<Contract, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const result = await http.post('/procurement/contracts', data);
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建合同失败'
    };
  }
};

// 更新合同
export const updateContract = async (id: number, data: Partial<Contract>) => {
  try {
    const result = await http.put(`/procurement/contracts/${id}`, data);
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新合同失败'
    };
  }
};

// 删除合同
export const deleteContract = async (id: number) => {
  try {
    const result = await http.delete(`/procurement/contracts/${id}`);
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除合同失败'
    };
  }
};